<?php
set_include_path($_SERVER ['DOCUMENT_ROOT']);
include_once 'admin/includes/functions/admin-functions.php';
include_once 'admin/includes/functions/report-functions.php';
global $DBobject, $SMARTY, $CONFIG;

if (empty($_SESSION['user']['admin'])) {
    echo json_encode(array(
      'html' =>  "Your session has expired. Please <a href='/admin/login'>login</a>."
    ));
    die();
}

$data = array();
switch ($_POST['action']) {
    case 'locationsfilter':
        $fparams = array();
        if (!empty($_SESSION['user']['admin']['franchisee'])) {
            $n=1;
            $tmpsql=array();
            foreach ($_SESSION['user']['admin']['franchisee'] as $m) {
                $tmpsql[] ="location_franchisee_id = :franchisee{$n}";
                $fparams[":franchisee{$n}"] = $m;
                $n++;
            }
            $sql_franchisee = " AND (".implode(" OR ", $tmpsql).") ";
        }
        $regionStr = '';
        if (!empty($_POST['termregions'])) {
            $regionArr = array();
            $n=1;
            foreach ($_POST['termregions'] as $rg) {
                $regionArr[] = "location_state = :location{$n}";
                $fparams[":location{$n}"] = $rg;
                $n++;
            }
            $regionStr = " AND (" . implode(' OR ', $regionArr).")";
        }
        if (!empty($_POST['regions'])) {
            $regionArr = array();
            $n=1;
            foreach ($_POST['regions'] as $rg) {
                $regionArr[] = "location_region_id = :region{$n}";
                $fparams[":region{$n}"] = $rg;
                $n++;
            }
            $regionStr .= " AND (" . implode(' OR ', $regionArr).")";
        }
        $locationsql = "SELECT location_suburb,location_name, location_object_id FROM tbl_location WHERE location_deleted IS NULL AND location_published = 1 AND location_listing_id = 9{$regionStr}{$sql_franchisee} ORDER BY location_suburb, location_name";
              
        if ($location = $DBobject->wrappedSql($locationsql, $fparams)) {
            $locationlist = array();
            foreach ($location as $l) {
                $locationlist[] = array("id"=>$l['location_object_id'],"value"=>unclean($l['location_suburb']) .' - '. unclean($l['location_name']));
            }
        }
        //	die(var_dump($locationsql). var_dump($fparams));
        echo json_encode(array('locationlist'=>$locationlist));
        die();
    case 'classlist':
        $res = studentlist(null, $_POST['terms'], $_POST['locations'], null, $_POST['filter']);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-classlist.tpl');
        echo json_encode($data);
        die();
    case 'revenuelist':
        $res = revenuelist(null, $_POST['terms'], $_POST['locations'], $_POST['filter']);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-revenue.tpl');
        echo json_encode($data);
        die();
    case 'enrolmentlist':
        $res = enrolmentlist(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], null);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-enrolments.tpl');
        echo json_encode($data);
        die();
    case 'triallist':
        $res = triallist(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], array('T'));
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-triallist.tpl');
        echo json_encode($data);
        die();
    case 'studentstatuslist':
        $res = studentstatuslist(null, $_POST['terms'], $_POST['locations'], $_POST['filter']);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-studentstatus.tpl');
        echo json_encode($data);
        die();
    case 'dailypaymentlist':
        $res = dailypaymentlist2(null, $_POST['terms'], $_POST['locations'], $_POST['filter']);
        $SMARTY->assign("classterms", $res);
            $res = makeapaymentlist($_POST['filter']);
        $SMARTY->assign("paytypes", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-dailypayments2.tpl');
        echo json_encode($data);
        die();
//       $res = dailypaymentlist(null,$_POST['terms'],$_POST['locations'],null,$_POST['filter']);
//       $SMARTY->assign("classterms",$res);
//       $data["html"] = $SMARTY->fetch('reports/output/report-dailypayments.tpl');
//       echo json_encode($data);
//       die();
    case 'paymentlist':
        $res = paymentlist(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], null);
        $SMARTY->assign("paymenttypes", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-paymentsreceived.tpl');
        echo json_encode($data);
        die();
    case 'reenrolmentlist':
        $res = reenrolmentlist(null, $_POST['terms'], $_POST['locations'], $_POST['filter']);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-reenrolment.tpl');
        echo json_encode($data);
        die();
    case 'trialconversionlist':
        $res = trialconversionlist(null, $_POST['terms'], $_POST['locations'], $_POST['filter']);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-trialconversions.tpl');
        echo json_encode($data);
        die();
    case 'enrolmentcomparisonlist':
        $res = reenrolmentlist(null, $_POST['terms'], $_POST['locations'], $_POST['filter']);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-enrolmentcomparison.tpl');
        echo json_encode($data);
        die();
    case 'revenuecomparisonlist':
        $res = revenuecomparisonlist(null, $_POST['terms'], $_POST['locations'], $_POST['filter']);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-revenuecomparison.tpl');
        echo json_encode($data);
        die();
    case 'averagerevenuelist':
        $res = averagerevenuelist(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], null);
        $SMARTY->assign("revenue", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-avgrevenue.tpl');
        echo json_encode($data);
        die();
    case 'averageenrolmentslist':
        $res = averageenrolmentslist(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], null);
        $SMARTY->assign("enrolments", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-avgenrolments.tpl');
        echo json_encode($data);
        die();
    case 'capacitylist':
        $res = enrolmentlist(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], null);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-capacity.tpl');
        echo json_encode($data);
        die();
    case 'referrallist':
        $res = referrallist(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], null);
        $SMARTY->assign("referrals", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-referralsources.tpl');
        echo json_encode($data);
        die();
    case 'toplocationslist':
        $res = toplocationslist(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], null);
        $SMARTY->assign("toplocations", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-toplocations.tpl');
        echo json_encode($data);
        die();
    case 'warninglist':
        $res = warninglist(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], null);
        $SMARTY->assign("warnings", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-warnings.tpl');
        echo json_encode($data);
        die();
    case 'limitedenrolmentslist':
        $res = limitedenrolmentslist(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], null);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-limitedenrolments.tpl');
        echo json_encode($data);
        die();
    case 'smsusage':
        $res = smsusage(null, $_POST['terms'], $_POST['locations'], $_POST['filter'], null, $_POST['sms_start_date'], $_POST['sms_end_date']);
        $SMARTY->assign("start_date", $_POST['sms_start_date']);
        $SMARTY->assign("end_date", $_POST['sms_end_date']);
        $SMARTY->assign("data", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-smsusage.tpl');
        echo json_encode($data);
        die();
    case 'memberdetails':
        $res = studentlist(null, $_POST['terms'], $_POST['locations'], null, $_POST['filter']);
        $SMARTY->assign("classterms", $res);
        $data["html"] = $SMARTY->fetch('reports/output/report-memberdetails.tpl');
        echo json_encode($data);
        die();
}

if (empty($_SESSION['user']['admin']['franchisee'])) {
    $franchisees = array();
    $fsql = "SELECT franchisee_object_id,CONCAT(franchisee_name,' (',admin_name,' ',admin_surname,') Tel:',admin_telephone) AS franchisee_name FROM tbl_franchisee LEFT JOIN tbl_access ON franchisee_object_id = access_franchisee_id LEFT JOIN tbl_admin ON access_admin_id = admin_id WHERE franchisee_deleted IS NULL AND franchisee_published = 1 AND access_deleted IS NULL AND admin_deleted IS NULL AND admin_level = 2 GROUP BY franchisee_name ORDER BY franchisee_name";
    if ($franchisees = $DBobject->wrappedSql($fsql)) {
        $SMARTY->assign("franchiseelist", $franchisees);
    }
}

$years = array();
$yrsql = "SELECT MIN(YEAR(term_start_date)) AS minyear,MAX(YEAR(term_end_date)) AS maxyear FROM tbl_term WHERE term_deleted IS NULL AND term_published = 1";
if ($yrres = $DBobject->wrappedSql($yrsql)) {
    for ($i = $yrres[0]['minyear']; $i <=$yrres[0]['maxyear']; $i++) {
        $years[]=$i;
    }
    $SMARTY->assign("yearlist", $years);
}

$statesql = "SELECT DISTINCT(term_region) AS term_region FROM tbl_term WHERE term_deleted IS NULL AND term_published = 1";
if ($stateres = $DBobject->wrappedSql($statesql)) {
    $SMARTY->assign("statelist", $stateres);
}
$fparams = array();
if (!empty($_SESSION['user']['admin']['franchisee'])) {
    $n=1;
    $tmpsql=array();
    foreach ($_SESSION['user']['admin']['franchisee'] as $m) {
        $tmpsql[] ="location_franchisee_id = :franchisee{$n}";
        $fparams[":franchisee{$n}"] = $m;
        $n++;
    }
    $sql_franchisee = " AND (".implode(" OR ", $tmpsql).") ";
}
$termssql = "SELECT term_object_id,term_name,term_region FROM tbl_term LEFT JOIN tbl_classterm ON classterm_term_id = term_id LEFT JOIN tbl_class ON classterm_class_id = class_object_id LEFT JOIN tbl_location ON location_object_id = class_location_id
		WHERE term_deleted IS NULL AND term_published = 1 AND class_deleted IS NULL AND class_published = 1 AND classterm_deleted IS NULL AND classterm_published = 1 AND location_deleted IS NULL {$sql_franchisee}  GROUP BY term_object_id ORDER BY term_start_date DESC";
if ($termres = $DBobject->wrappedSql($termssql, $fparams)) {
    $SMARTY->assign("termlist", $termres);
}

/* === REGIONS - NOT AVAILABLE YET === 
$agesql = "SELECT region_id,region_name FROM tbl_region WHERE region_deleted IS NULL";
if($regionres = $DBobject->wrappedSql($agesql)){
	$SMARTY->assign("regionlist",unclean($regionres));
} */
$locationsql = "SELECT location_suburb,location_name, location_object_id,location_state FROM tbl_location WHERE location_deleted IS NULL AND location_published = 1 AND location_listing_id = 9 {$sql_franchisee} ORDER BY location_suburb, location_name";
if ($locationres = $DBobject->wrappedSql($locationsql, $fparams)) {
    $SMARTY->assign("locationlist", unclean($locationres));
}
$agesql = "SELECT agegroup_id,agegroup_name FROM tbl_agegroup WHERE agegroup_deleted IS NULL";
if ($ageres = $DBobject->wrappedSql($agesql)) {
    $SMARTY->assign("agegrouplist", unclean($ageres));
}

$SMARTY->assign("weekdaylist", array(array("id"=>"1","display"=>"星期一","value"=>"%Monday%"),array("id"=>"2","display"=>"星期二","value"=>"%Tuesday%"),array("id"=>"3","display"=>"星期三","value"=>"%Wednesday%"),array("id"=>"4","display"=>"星期四","value"=>"%Thursday%"),array("id"=>"5","display"=>"星期五","value"=>"%Friday%"),array("id"=>"6","display"=>"星期六","value"=>"%Saturday%"),array("id"=>"7","display"=>"星期日","value"=>"%Sunday%")));


function generateCSV($filename, $data)
{

    $csv = RecursiveAssociativeArrayToCSV($data);
    $filename=str_replace(".csv", "", $filename).".".date("Y-m-d").".csv";
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: " . strlen($csv));
    header("Content-type: text/x-csv");
    header("Content-Disposition: attachment; filename=".$filename);
    echo $csv;
    die();
}
